package com.renchi.menu.User.service;

import com.renchi.menu.User.dao.UserDbDao;
import com.renchi.menu.User.entity.UserDbEntity;
import com.renchi.menu.common.http.HttpClientUtil;
import com.renchi.menu.common.json.JsonUtils;
import com.renchi.menu.common.random.RandomUtil;
import com.renchi.menu.common.result.Result;
import com.renchi.menu.common.result.ResultTools;
import com.renchi.menu.common.wechat.WXSessionModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserDbService {
    @Autowired
    private UserDbDao userDbDao;

    @Value("${wechat.appid}")
    private String APPID;
    @Value("${wechat.secret}")
    private String SECRET;

    public Result getOpenid(String code){
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String,String> param = new HashMap<>();
            param.put("appid",APPID);
            param.put("secret",SECRET);
            param.put("js_code",code);
            param.put("grant_type","authorization_code");
            String wxResult= HttpClientUtil.doGet(url,param);
            WXSessionModel model= JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);
            Map<String,Object>  map = new HashMap<>();
            map.put("openid",model.getOpenid());
            if (model.getOpenid()!=null){
                return ResultTools.result(0,"",map);
            }
            return ResultTools.result(404,"失败",null);
        }catch (Exception e){
            return ResultTools.result(404,e.getMessage(),null);
        }
    }

    public Result saveUser(UserDbEntity userDbEntity){
        try {
            userDbDao.save(userDbEntity);
            return ResultTools.result(0,"",null);
        }catch (Exception e){
            log.error("保存用户失败");
            return ResultTools.result(404,e.getMessage(),null);
        }
    }

    public Result delUser(String user_id){
        try {
            userDbDao.deleteById(user_id);
            return ResultTools.result(0,"",null);
        }catch (Exception e){
            log.error("删除用户失败");
            return ResultTools.result(404,e.getMessage(),null);
        }
    }
}
